package cz.spock.core.util;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * TODO test performance
 * 
 * @author miso
 *
 */
public class SpockUrlFilter implements Filter {
    
    private FilterConfig filterConfig;
    private static final Logger log = Logger.getLogger(SpockUrlFilter.class.getName());

    /**
     * main filter, redirects requested urls to proper controllers/jsps
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // *.jsp are excluded from dispatcher servlet
        String uri = ((HttpServletRequest) request).getRequestURI();
        if (uri.endsWith(".jsp") || uri.startsWith("/_ah") || uri.startsWith("/j_spring_security_check")) {
            System.out.println("uri " + uri.toString() + " excluded from servlet process");
            chain.doFilter(request, response); // Just let it go (assuming that files are in real not placed in a /spring folder!)
            return;
        } else if(uri.startsWith("/cms")) {
            System.out.println("/cms* requested, redirection to /spring/cms*");
            request.getRequestDispatcher("/spring" + uri).forward(request, response); // Pass to Spring dispatcher servlet.
        } else if(uri.endsWith(".css")) {
            System.out.println("Css requested.");
            request.getRequestDispatcher("/spring/css" + uri).forward(request, response); // Pass to Spring dispatcher servlet.
        } else if(uri.startsWith("/admin")) {
            System.out.println("Admin url requested.");
            request.getRequestDispatcher("/spring" + uri).forward(request, response); // Pass to Spring dispatcher servlet.            
        } else {
            System.out.println(uri.toString() + " requested, redirection to /web" + uri.toString());
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/spring/web"+uri);
            requestDispatcher.forward(request,response);
        }
    }

    @Override
    public void init(FilterConfig fc) throws ServletException {
        this.filterConfig = fc;
    }
    
    @Override
    public void destroy() {
    }
    
    public FilterConfig getFilterConfig() {
        return filterConfig;
    }

}
